package com.yonyou.common.git;

import com.intellij.notification.NotificationType;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.yonyou.biz.vo.GitLogContext;
import com.yonyou.demo.UserListPanel;
import git4idea.branch.GitBranchUtil;
import git4idea.repo.GitRemote;
import git4idea.repo.GitRepository;
import org.apache.commons.collections.CollectionUtils;
import org.gitlab4j.api.*;
import org.gitlab4j.api.models.*;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class GiLogMRProcess extends Task.Backgroundable {

    private GitLogContext context;
    private UserListPanel userListPanel;
    private String branch ;
    private GitRepository currentRepository;
    private GitLabApi gitLabApi;
    @Override
    public void run(@NotNull ProgressIndicator progressIndicator) {
        // 设置进度条为模糊进度条
        progressIndicator.setIndeterminate(true);
        // 这里就是我们需要模拟执行我们相关的业务逻辑的部分，此处就使线程睡眠3秒作为模拟
        try {
            final String currentBranch = currentRepository.getCurrentBranch().getName();
            Collection<GitRemote> remotes = currentRepository.getRemotes();
            String remoteUrl = remotes.iterator().next().getUrls().get(0);
            this.gitLabApi = new GitLabApi(remoteUrl.substring(0,remoteUrl.indexOf("com")+4),this.userListPanel.getGit_token().getText());
            IssuesApi issuesApi = this.gitLabApi.getIssuesApi();
            IssueFilter fi =new IssueFilter();
            fi.withState(Constants.IssueState.OPENED);
            fi.withSearch("switch");
            final List<Issue> issues = issuesApi.getIssues(userListPanel.getGitProject(this.gitLabApi,currentRepository).getId(), fi);
            if(CollectionUtils.isNotEmpty(issues)){
                String str2=String.format("源分支：%s  目标分支：%s  ,结果：不支持代码合并、请联系管理员开启权限！",currentBranch,branch);
                com.yonyou.ctm.ctmplugin.utils.NotificationUtil.showErrDialog("操作异常",str2);
                return ;
            }
            meryCode(currentBranch,branch);
        } catch (Exception e) {
            com.yonyou.ctm.ctmplugin.utils.NotificationUtil.showNotification(NotificationType.ERROR,e.getMessage());
        }finally {
            // 开启进度条
            progressIndicator.setIndeterminate(true);
            // 设置进度条为百分百
            progressIndicator.setFraction(1.0);
        }
    }

    public GiLogMRProcess(GitLogContext context,String branch , UserListPanel userListPanel,GitRepository currentRepository) {
        super(context.getProject(), "自动合并，提交至："+branch);
        this.userListPanel = userListPanel;
        this.context = context;
        this.branch = branch;
        this.currentRepository = currentRepository;
    }


    public boolean meryCode(String currentBranch,String targetBranch) throws Exception {

        final MergeRequestApi mergeRequestApi = this.gitLabApi.getMergeRequestApi();
        MergeRequest mr = null;
        Long assinID=null;
        try{
            assinID=Long.parseLong(userListPanel.getShenpiren().getText());
        }catch(Exception e){
        }
        try {
            boolean isbugfix=currentBranch.toLowerCase().contains("bugfix");
            String title=null;
            String description=null;
            if(isbugfix){
                title="[bugfix=问题修复]:全自动合并到部分分支(非保护分支)";
                description="【问题修复】"+"非手动确认合并:源分支：" + currentBranch + "=> 目标分支："+targetBranch;
            }else{
                title="[features=特性上线]:半自动合并到全部分支";
                description="【特性上线】"+"需手动确认合并:源分支：" + currentBranch + "=> 目标分支："+targetBranch;
            }
            MergeRequestParams mr_params=new MergeRequestParams()
                    .withSourceBranch(currentBranch)
                    .withTargetBranch(targetBranch)
                    .withTitle(title)
                    .withDescription(description)
                    .withAssigneeId(assinID)
                    .withReviewerIds(Arrays.asList(assinID));
            mr = mergeRequestApi.createMergeRequest(this.userListPanel.getGitProject( this.gitLabApi,currentRepository).getId(),mr_params);
            /*6809*/
            int count=0;
            final List<ProtectedBranch> protectedBranches =  this.gitLabApi.getProtectedBranchesApi().getProtectedBranches(this.userListPanel.getGitProject( this.gitLabApi, currentRepository).getId());
            final List<String> collect = protectedBranches.stream().map(ProtectedBranch::getName).collect(Collectors.toList());
            //不问题修复、和不保护的分支 自动合并
            boolean isautoMR =isbugfix&&!collect.contains(targetBranch);
            while (isautoMR) {
                //String str1=String.format("源分支：%s\n目标分支：%s：\n结果：查询合并状态中！",targetBranch,currentBranch,targetBranch);
                //com.yonyou.ctm.ctmplugin.utils.NotificationUtil.showNotification(NotificationType.INFORMATION,str1);
                MergeRequestFilter filter = new MergeRequestFilter();
                filter.setProjectId(this.userListPanel.getGitProject( this.gitLabApi,currentRepository).getId());
                filter.setIids(Arrays.asList(mr.getIid()));
                MergeRequest mergeRequests =  mergeRequestApi.getMergeRequests(filter).get(0);
                final String mergeStatus = mergeRequests.getMergeStatus();
                if ("can_be_merged".equals(mergeStatus)) {
                    mergeRequestApi.acceptMergeRequest(this.userListPanel.getGitProject(this.gitLabApi,currentRepository).getId(),mergeRequests.getIid());
                    String str2=String.format("源分支：%s  目标分支：%s ,结果：代码已自动合并成功！",currentBranch,targetBranch,targetBranch);
                    com.yonyou.ctm.ctmplugin.utils.NotificationUtil.showNotification(NotificationType.INFORMATION,str2);
                    break;
                }
                if ("cannot_be_merged".equals(mergeStatus)) {
                    String str2=String.format("源分支：%s  目标分支：%s  ,结果：该提交记录可能已被合并或存在冲突、请检查:%s",currentBranch,targetBranch,mergeRequests.getWebUrl());
                    com.yonyou.ctm.ctmplugin.utils.NotificationUtil.showNotification(NotificationType.WARNING,str2);
                    MergeRequestParams params=new MergeRequestParams();
                    params.withStateEvent(Constants.StateEvent.CLOSE);
                    params.withTitle("该提交记录可能已被合并或存在冲突，自动关闭");
                    mergeRequestApi.updateMergeRequest(this.userListPanel.getGitProject(this.gitLabApi,currentRepository).getId(),mergeRequests.getIid(),params);
                    break;
                }
                if(count>=20){
                    //String str2=String.format("源分支：%s\n目标分支：%s\n,结果：合并超时、请查看：%s",currentBranch,targetBranch,mr.getWebUrl());
                    //throw new Exception(str2);
                    mergeRequestApi.acceptMergeRequest(this.userListPanel.getGitProject(this.gitLabApi,currentRepository).getId(),mergeRequests.getIid());
                    String str2=String.format("源分支：%s\n目标分支：%s\n,结果：代码已自动合并成功！",currentBranch,targetBranch,targetBranch);
                    com.yonyou.ctm.ctmplugin.utils.NotificationUtil.showNotification(NotificationType.INFORMATION,str2);
                    break;
                }
                Thread.sleep(1500);
                count++;

            }
            if(!isautoMR){
                String str2=String.format("源分支：%s  目标分支：%s  ,结果：此次合并为特性上线或目标分支为保护分支、请手动合并！:%s",currentBranch,targetBranch,mr.getWebUrl());
                com.yonyou.ctm.ctmplugin.utils.NotificationUtil.showNotification(NotificationType.INFORMATION,str2);
            }
            return true;
        }catch (Exception e){
            System.err.println(e);
            //该提交记录已被合并到当前分支、忽略！！！！！！
            //self.insertText( "【%s】该提交记录已被合并到当前分支、忽略！！！！！！\n"% (branch), "background_yellow")
            //if(null!=mr){
            //    MergeRequestParams params=new MergeRequestParams();
            //    params.withStateEvent(Constants.StateEvent.CLOSE);
            //    params.withTitle("该提交记录可能已被合并或存在冲突，自动关闭");
            //    this.userListPanel.getMergeRequestApi().updateMergeRequest(this.userListPanel.getGitProject().getId(),mr.getIid(),params);
            //}
            com.yonyou.ctm.ctmplugin.utils.NotificationUtil.showNotification(NotificationType.ERROR,e.getMessage());
            return false;
        }

    }

}
